//----------------------------------------------
//            NGUI: Next-Gen UI kit
// Copyright © 2011-2015 Tasharen Entertainment
//----------------------------------------------

using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// Tween the object's alpha. Works with both UI widgets as well as renderers.
/// </summary>

[AddComponentMenu("NGUI/Tween/Tween Alpha")]
public class TweenAlpha : UITweener
{
    [Range(0f, 1f)]
    public float from = 1f;
    [Range(0f, 1f)]
    public float to = 1f;
    [System.NonSerialized]
    public bool IncludeChildren = true;
    bool mCached = false;
    private MaskableGraphic _uguiElement;
    private MaskableGraphic[] _childrenGraphicElements;
    [System.Obsolete("Use 'value' instead")]
    public float alpha { get { return this.value; } set { this.value = value; } }

    void Cache()
    {
        mCached = true;
        _uguiElement = GetComponent<MaskableGraphic>();

        if (_uguiElement == null)
        {
            _uguiElement = GetComponentInChildren<MaskableGraphic>();
        }
        if (IncludeChildren)
        {
            _childrenGraphicElements = GetComponentsInChildren<MaskableGraphic>();
        }
    }
    public float value
    {
        get
        {
            if (!mCached) Cache();

            return _uguiElement != null ? _uguiElement.color.a : 1f;
        }
        set
        {
            if (!mCached) Cache();

            if (_uguiElement != null)
            {
                Color c = _uguiElement.color;
                c.a = value;
                _uguiElement.color = c;
            }
            if (_childrenGraphicElements != null && _childrenGraphicElements.Length > 0)
            {
                int cnt = _childrenGraphicElements.Length;
                for (int i = 0; i < cnt; i++)
                {
                    var childElement = _childrenGraphicElements[i];
                    Color c = childElement.color;
                    c.a = value;
                    childElement.color = c;
                }
            }
        }
    }
    protected override void OnUpdate(float factor, bool isFinished) { value = Mathf.Lerp(from, to, factor); }

    static public TweenAlpha Begin(GameObject go, float duration, float alpha)
    {
        TweenAlpha comp = UITweener.Begin<TweenAlpha>(go, duration);
        comp.from = comp.value;
        comp.to = alpha;

        if (duration <= 0f)
        {
            comp.Sample(1f, true);
            comp.enabled = false;
        }
        return comp;
    }

    public override void SetStartToCurrentValue() { from = value; }
    public override void SetEndToCurrentValue() { to = value; }
}
